package kernel.udp.server;

import java.awt.*;
import java.net.*;
import java.io.*;

import kernel.udp.requests.HandlerFinder;
import kernel.udp.requests.RequestHandler;

public class UDPServer{
  
  
	HandlerFinder myHandlerManager = new HandlerFinder();
	

	Thread thread;
	DatagramSocket socket;
	int Port;

  
	
	public void start(){
		new StartThread();
	}
	
	public UDPServer(int port){	
				
		Port=port;	  
		
	  
	}
	
	public void addHandler(String ServiceClusterName, Class myClass){
		
		myHandlerManager.addHandler(ServiceClusterName, myClass);
		System.out.println("[ "+"UDP CLIENT"+" ] "+"[ Server ] Loaded Service: "+ServiceClusterName+" -> "+myClass);
	}
	
	
	
  

	public class StartThread implements Runnable{
    
		StartThread(){      
			thread = new Thread(this);      
			thread.start();      
			}
		public void run(){
			try{
				byte[] buffer = new byte[4096];
				int port = Port;
				String message;
				try{
					socket = new DatagramSocket(port);
					System.out.println("[ "+"UDP CLIENT"+" ] "+"UDP Server["+port+"] is started.\n");
					while(true){
						try{
							
							//Receive request from client
							DatagramPacket packet = new DatagramPacket(buffer, buffer.length );
							socket.receive(packet);
							InetAddress client = packet.getAddress();
							int client_port = packet.getPort();
							System.out.println("[ "+"UDP CLIENT"+" ] "+"[Incoming Req] "+new String(buffer)+" from "+client);
							String reqString = new String(buffer).trim();
							reqString = reqString.substring(0,reqString.indexOf("<?>"));
							RequestHandler myHandler = new RequestHandler(reqString, socket, client, client_port, myHandlerManager);
							myHandler.start();
							}
						catch(UnknownHostException ue){}
						}
					}
				catch(java.net.BindException b){}
				}
			catch (IOException e){
				System.err.println("[ "+"UDP CLIENT"+" ] "+e);
				}
			}
		}
	} 